package com.qinggeng.project.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.qinggeng.common.enums.OrdersDistTypeEnum;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.DistributionPoint;
import com.qinggeng.project.system.domain.Orders;
import com.qinggeng.project.system.domain.OrdersDist;
import com.qinggeng.project.system.domain.json.DistPriceConfig;
import com.qinggeng.project.system.domain.json.DistTime;
import com.qinggeng.project.system.domain.json.Price;
import com.qinggeng.project.system.mapper.DistributionPointMapper;
import com.qinggeng.project.system.mapper.OrdersDistMapper;
import com.qinggeng.project.system.mapper.OrdersMapper;
import com.qinggeng.project.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

/**
 * @author 吴鹏飞
 * @date 2020/9/22
 */
@Service
public class OrdersDistServiceImpl implements OrdersDistService {

    public static final java.lang.String DIST_PRICE_KEY="sys.orders.distPrice";


    public static final String DIST_TIME_KEY="sys.orders.distTime";

    public static final String PICK_TIME_KEY="sys.orders.distTime";


    @Resource
    private OrdersDistMapper ordersDistMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private ISysConfigService configService;
    @Resource
    private DistributionPointMapper distributionPointMapper;
    @Autowired
    private IOrdersGoodsService ordersGoodsService;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 根据订单编号查询订单配送信息
     * @param ordersNo
     * @return
     */
    public OrdersDist selectOrdersDistByOrdersNo(String ordersNo) {
        Orders orders = ordersMapper.selectOrdersByOrdersNo(ordersNo);
        if (orders == null){
            throw new CustomException("订单不存在", ShowTypeEnum.用户.getValue());
        }
        Long courierId = sysUserService.selectUserIdByPhoneNumberAndUserType(ApiUtils.getApiUser().getUser().getPhonenumber(), UserTypeEnum.COURIER.getCode());
        if (courierId == null){
            throw new CustomException("当前用户没有自提点账号,courierId="+courierId);
        }
        DistributionPoint distributionPoint = distributionPointMapper.selectDistributionPointByCourierId(courierId);
        if (distributionPoint == null){
            throw new CustomException("配送点不存在");
        }
        OrdersDist ordersDist=ordersDistMapper.selectOrdersDistByOrdersNo(ordersNo,distributionPoint.getId());
        //计算订单的商品提成
        BigDecimal ordersPercentage=ordersGoodsService.getOrdersPercentageByOrdersId(orders.getOrdersId());
        //订单提成=配送费+商品提成
        ordersDist.setPercentage(ordersDist.getDistPrice().add(ordersPercentage));
        return ordersDist;
    }

    @Override
    public BigDecimal getDistPrice(BigDecimal totalPrice,String distType) {

        DistPriceConfig priceConfig=this.getDistPriceConfig();
        //自定义费用
        if(distType.equals(OrdersDistTypeEnum.自取.getValue())){
            return getDividePrice(totalPrice,priceConfig.getDividePrice(),priceConfig.getPickPrice());
        }
        if (distType.equals(OrdersDistTypeEnum.配送.getValue())) {
            return getDividePrice(totalPrice,priceConfig.getDividePrice(),priceConfig.getDistPrice());
        }
        return new BigDecimal(0);
    }

    /**
     * 计算配送点收益
     * @param orders
     * @return
     */
    @Override
    public BigDecimal getPointPrice(Orders orders){
        if(null==orders){
            throw new CustomException("订单不存在");
        }
        //订单总额为0元时，配送点收益为0
        if(null==orders.getTotalPrice()||orders.getTotalPrice().compareTo(new BigDecimal(0))==0){
            return new BigDecimal(0);
        }
        DistPriceConfig priceConfig=this.getDistPriceConfig();
        //自取收益
        if(orders.getDistType().equals(OrdersDistTypeEnum.自取.getValue())){
            return getDividePrice(orders.getTotalPrice(),priceConfig.getDividePrice(),priceConfig.getPickPointPrice());
        }
        //配送收益
        if(orders.getDistType().equals(OrdersDistTypeEnum.配送.getValue())){
            return getDividePrice(orders.getTotalPrice(),priceConfig.getDividePrice(),priceConfig.getPickPointPrice());
        }
        return new BigDecimal(0);
    }

    //获取划分价格
    private BigDecimal getDividePrice(BigDecimal totalPrice, BigDecimal dividePrice, Price price){
        if(totalPrice.compareTo(dividePrice)<0){
            return price.getWithin();
        }
        return price.getBeyond();
    }

    @Override
    public DistPriceConfig getDistPriceConfig() {
        return JSON.parseObject(configService.getConfigValue(DIST_PRICE_KEY), DistPriceConfig.class);
    }

    public DistTime getDistTimeConfig(String distType){
        //获取配送时间的配置文件
        if(distType.equals(OrdersDistTypeEnum.配送.getValue())){
            return JSON.parseObject(configService.getConfigValue(DIST_TIME_KEY),DistTime.class);
        }else if(distType.equals(OrdersDistTypeEnum.自取.getValue())){
            return JSON.parseObject(configService.getConfigValue(PICK_TIME_KEY),DistTime.class);
        }else{
            throw new CustomException("不支付的配送方式");
        }
    }
    @Override
    public Date getTime(com.qinggeng.project.system.domain.json.Calendar time){
        Calendar calendar =Calendar.getInstance();
        calendar.add(Calendar.DATE,time.getAddDay());
        calendar.set(Calendar.HOUR_OF_DAY,time.getHour());
        calendar.set(Calendar.MINUTE,time.getMinute());
        return calendar.getTime();
    }

    public Date getDivideTime(String distType){
        return this.getTime(this.getDistTimeConfig(distType).getDivide());
    }

    public Date getDivideTime(Date shipTime,String distType){
        com.qinggeng.project.system.domain.json.Calendar divideTime=this.getDistTimeConfig(distType).getDivide();
        Calendar calendar =Calendar.getInstance();
        calendar.setTime(shipTime);
        calendar.set(Calendar.HOUR_OF_DAY,divideTime.getHour());
        calendar.set(Calendar.MINUTE,divideTime.getMinute());
        return calendar.getTime();
    }
}
